/*
   Copyright 2009 Ryan Phillips

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
#include <apr.h>
#include <apr_network_io.h>
#include <apr_poll.h>
#include <apr_buckets.h>
#include <apr_strings.h>
#include <apr_signal.h>
#include <apr_thread_proc.h>
#include <apr_getopt.h>
#include <error.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/inotify.h>
#include "remotecores.h"

typedef struct conn_baton_t
{
    apr_socket_t *sock;
    apr_pool_t *pool;
} conn_baton_t;

static remotecores_error_t *serve(apr_pool_t * pool, apr_uint32_t daemon, 
                                  const char *host, apr_port_t port);

static void usage(apr_pool_t * pool);

static const apr_getopt_option_t server_options[] = {
    {"hostname",  'n', 1, "hostname"},
    {"port",      'p', 1, "Port of server"},
    {"daemon",    'd', 0, "run in daemon mode"},
    {"help",      'h', 0, "Help"},
    {0, 0, 0, 0},
};

int main(int argc, const char **argv)
{
    remotecores_error_t *err;
    apr_pool_t *g_pool;
    apr_getopt_t *os;
    apr_status_t rv;
    int opt;
    const char *arg;
    const char *host = NULL;
    apr_uint32_t daemon = TRUE;
    apr_port_t port = REMOTECORES_DEFAULT_PORT;

    /* Init */
    apr_initialize();
    apr_pool_create(&g_pool, NULL);

    /* Parse Commandline */
    rv = apr_getopt_init(&os, g_pool, argc, argv);
    if (rv != APR_SUCCESS) {
        err = remotecores_error_create(rv, "apr_getopt_init");
        return err->err;
    }

    while (1) {
        rv = apr_getopt_long(os, server_options, &opt, &arg);
        if (APR_STATUS_IS_EOF(rv)) {
            break;
        }

        if (rv != APR_SUCCESS) {
            usage(g_pool);
        }

        switch (opt) {
        case 'n':
            host = arg;
            break;
        case 'p':
            port = atoi(arg);
            break;
        case 'h':
            usage(g_pool);
            break;
        case 'd':
            daemon = FALSE;
            break;
        }
    }

    if (host == NULL) {
        usage(g_pool);
    }

    /* Run */
    err = serve(g_pool, daemon, host, port);
    if (err) {
        fprintf(stderr, "[%s:%d] %s (%d)" APR_EOL_STR,
                err->file, err->line, err->msg, err->err);
    }

    /* Cleanup */
    apr_pool_destroy(g_pool);
    apr_terminate();

    return 0;
}

static void *APR_THREAD_FUNC serve_thread(apr_thread_t * tid, void *data)
{
    remotecores_error_t *err;
    conn_baton_t *conn = (conn_baton_t *) data;
    apr_status_t rv;
    apr_file_t *file;
    apr_size_t nbytes, o, i;

    apr_uint32_t protocol_version = 0;
    apr_off_t coresize;
    char *filename;
    char core_buffer[8 * 1024];
    remotecores_protocol_t *proto;

    (void) tid;

    /* Read from wire */
    remotecores_protocol_create(&proto, conn->sock, conn->pool);
    err = remotecores_uint32_read(proto, &protocol_version);
    if (err) {
        fprintf(stderr, "[%s:%d] %s (%d)" APR_EOL_STR,
                err->file, err->line, err->msg, err->err);
    }

    err = remotecores_string_read(proto, &filename);
    if (err) {
        fprintf(stderr, "[%s:%d] %s (%d)" APR_EOL_STR,
                err->file, err->line, err->msg, err->err);
    }

    err = remotecores_offset_read(proto, &coresize);
    if (err) {
        fprintf(stderr, "[%s:%d] %s (%d)" APR_EOL_STR,
                err->file, err->line, err->msg, err->err);
    }

    fprintf(stderr,
            "remotecore-server: Writing Core (%s, %" APR_SIZE_T_FMT
            " bytes)\n", filename, coresize);

    /* Open file for writing */
    rv = apr_file_open(&file, filename, APR_WRITE | APR_CREATE,
                       APR_FPROT_OS_DEFAULT, conn->pool);
    if (rv != APR_SUCCESS) {
        err = remotecores_error_create(rv, "apr_file_open");
        return err;
    }

    /* Loop over socket until done */
    o = 0;
    i = coresize;
    while (i > 0) {
        nbytes = sizeof(core_buffer);
        rv = apr_socket_recv(conn->sock, core_buffer, &nbytes);
        if (rv != APR_SUCCESS) {
            err = remotecores_error_create(rv, "apr_socket_recv");
            return err;
        }

        apr_file_write(file, core_buffer, &nbytes);

        o += nbytes;
        i -= nbytes;
    }

    apr_file_close(file);

    fprintf(stderr, "remotecore-server: Writing Core Done\n");

    apr_socket_close(conn->sock);
    apr_pool_destroy(conn->pool);

    return NULL;
}

static remotecores_error_t *serve(apr_pool_t * pool, apr_uint32_t daemon, 
                                  const char *host, apr_port_t port)
{
    remotecores_error_t *err;
    apr_socket_t *sock;
    apr_sockaddr_t *sa;
    apr_status_t rv;

    rv = apr_sockaddr_info_get(&sa, host, APR_INET, port, 0, pool);
    if (rv != APR_SUCCESS) {
        err = remotecores_error_create(rv, "apr_sockaddr_info_get");
        return err;
    }

    rv = apr_socket_create(&sock, APR_INET, SOCK_STREAM, APR_PROTO_TCP, pool);
    if (rv != APR_SUCCESS) {
        err = remotecores_error_create(rv, "apr_socket_create");
        return err;
    }

    apr_socket_opt_set(sock, APR_SO_REUSEADDR, 1);

    rv = apr_socket_bind(sock, sa);
    if (rv != APR_SUCCESS) {
        err = remotecores_error_create(rv, "apr_socket_bind");
        return err;
    }

    apr_socket_listen(sock, 7);

    fprintf(stderr, "remotecore-server: Listening (%s:%i)\n", host, port);

    if (daemon) {
        apr_proc_detach(APR_PROC_DETACH_DAEMONIZE);
    }

    apr_signal(SIGPIPE, SIG_IGN);

    while (1) {
        conn_baton_t *baton;
        apr_threadattr_t *tattr;
        apr_thread_t *tid;
        apr_socket_t *usock;
        apr_pool_t *connection_pool;

        apr_pool_create(&connection_pool, NULL);

        rv = apr_socket_accept(&usock, sock, connection_pool);
        if (rv) {
            err = remotecores_error_create(rv, "apr_socket_accept");
            return err;
        }

        baton = (conn_baton_t *) apr_palloc(connection_pool, sizeof(*baton));
        baton->sock = usock;
        baton->pool = connection_pool;

        rv = apr_threadattr_create(&tattr, connection_pool);
        if (rv) {
            err = remotecores_error_create(rv, "apr_threadattr_create");
            return err;
        }

        rv = apr_threadattr_detach_set(tattr, 1);
        if (rv) {
            err = remotecores_error_create(rv, "apr_threadattr_detach_set");
            return err;
        }

        apr_thread_create(&tid, tattr, serve_thread, baton, connection_pool);
    }

    return REMOTECORES_SUCCESS;
}

static void usage(apr_pool_t * pool)
{
    (void) pool;
    fprintf(stderr, "[%s]\n", REMOTECORES_VERSION_STRING);
    fprintf(stderr, "usage: remotecore-server -n hostname [-p port]\n");
    exit(EXIT_SUCCESS);
}
